package com.xingxuecn.limit.dao.impl;

import com.xingxuecn.limit.common.model.Role;
import com.xingxuecn.limit.common.model.RoleUser;
import com.xingxuecn.limit.common.utils.DbUtils;
import com.xingxuecn.limit.dao.RoleUserDao;


import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author zgx at 2018/9/17 0017 上午 10:43
 */
public class RoleUserDaoImpl implements RoleUserDao {
    QueryRunner queryRunner = new QueryRunner(DbUtils.getDataSource());
    
    @Override
    public int add(RoleUser roleUser) throws SQLException {
        String sql = "insert into role_user(role_id,user_id) values(?,?)";
        return queryRunner.execute(sql, new Object[]{roleUser.getRole_id(), roleUser.getUser_id()});
    }

    @Override
    public int delete(RoleUser roleUser) throws SQLException {
        String sql = "delete from role_user where role_id = ? and user_id=?";
        return queryRunner.execute(sql, new Object[]{roleUser.getRole_id(), roleUser.getUser_id()});
    }

    @Override
    public List<Role> loadRoleByUser(Integer userId) throws SQLException {
        String sql = "select r.* from role r\n" +
                "inner join role_user ru on ru.role_id = r.id\n" +
                "where user_id = ?";

        return queryRunner.query(sql,new BeanListHandler<Role>(Role.class),userId);
    }
}
